//
//  UIImage+QSExtension.swift
//  TestSwift
//
//  Created by Song on 2018/4/19.
//  Copyright © 2018年 Song. All rights reserved.
//

import UIKit

extension UIImage {
    /// 添加文字水印
    ///
    /// - Parameters:
    ///   - text: 水印文字
    ///   - watermarkRect: 水印文字的位置
    ///   - attributes: 水印文字的一些属性设置
    /// - Returns: 带有水印的图片
    func qs_addWatermark(text: String, watermarkRect: CGRect, attributes: [NSAttributedStringKey : Any]) -> UIImage? {
        UIGraphicsBeginImageContext(size)
        draw(in: CGRect.init(x: 0, y: 0, width: size.width, height: size.height))
        
        if #available(iOS 7, *) {
            text.draw(in: watermarkRect, withAttributes: attributes)
        } else {
            text.draw(in: watermarkRect)
        }
        
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        
        return image
    }
    
    /// 添加图片水印
    ///
    /// - Parameters:
    ///   - waterImage: 水印图片
    ///   - watermarkRect: 水印图片的位置
    /// - Returns: 带有水印的图片
    func qs_addWatermark(waterImage: UIImage, watermarkRect: CGRect) -> UIImage? {
        UIGraphicsBeginImageContext(size)
        draw(in: CGRect.init(x: 0, y: 0, width: size.width, height: size.height))
        waterImage.draw(in: watermarkRect)
        
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        
        return image
    }
    
    /// 压缩图片到指定大小(质量大小，即data)
    ///
    /// - Parameter length: 图片大小
    /// - Returns: 压缩后的图片
    func qs_compressToLength(_ length: Int) -> UIImage? {
        var compress : CGFloat = 1.0
        var data = UIImageJPEGRepresentation(self, compress)
        
        guard var _ = data?.count else {
            return nil
        }
        
        while compress > 0.01 && (data?.count)! / 1000 > length {
            compress -= 0.02
            data = UIImageJPEGRepresentation(self, compress)
        }
        
        return UIImage.init(data: data!)
    }
    
    /// 将图片缩放成指定尺寸（多余部分自动删除）
    ///
    /// - Parameter newSize: 指定的尺寸
    /// - Returns: 缩放后的图片
    func qs_scaled(to newSize: CGSize) -> UIImage {
        // 计算比例
        let aspectWidth = newSize.width / size.width
        let aspectHeight = newSize.height / size.height
        let aspectRatio = max(aspectWidth, aspectHeight)
        
        // 图片绘制区域
        var scaledImageRect = CGRect.zero
        scaledImageRect.size.width = size.width * aspectRatio
        scaledImageRect.size.height = size.height * aspectRatio
        scaledImageRect.origin.x = (newSize.width - size.width * aspectRatio) / 2.0
        scaledImageRect.origin.y = (newSize.height - size.height * aspectRatio) / 2.0
        
        // 绘制并获取最终图片
        UIGraphicsBeginImageContext(newSize)
        draw(in: scaledImageRect)
        let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        
        return scaledImage!
    }
    
    /// 将图片裁剪成指定比例（多余部分自动删除）
    ///
    /// - Parameter ratio: 宽高比例
    /// - Returns: 裁剪后的图片
    func qs_crop(ratio: CGFloat) -> UIImage {
        // 计算最终尺寸
        var newSize: CGSize!
        if size.width / size.height > ratio {
            newSize = CGSize(width: size.height * ratio, height: size.height)
        }else{
            newSize = CGSize(width: size.width, height: size.width / ratio)
        }
        
        // 图片绘制区域
        var rect = CGRect.zero
        rect.size.width = size.width
        rect.size.height = size.height
        rect.origin.x = (newSize.width - size.width ) / 2.0
        rect.origin.y = (newSize.height - size.height ) / 2.0
        
        // 绘制并获取最终图片
        UIGraphicsBeginImageContext(newSize)
        draw(in: rect)
        let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        
        return scaledImage!
    }
    
    /// 生成一张纯色的图片
    ///
    /// - Parameters:
    ///   - solidColor: 图片颜色
    ///   - size: 图片大小
    /// - Returns: 生成的图片
    class func qs_createImage(solidColor: UIColor, size: CGSize) -> UIImage? {
        
        let rect = CGRect.init(origin: CGPoint.init(x: 0, y: 0), size: size)
        UIGraphicsBeginImageContext(size)
        
        let context = UIGraphicsGetCurrentContext()
        context?.setFillColor(solidColor.cgColor)
        context?.fill(rect)
        
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        
        return image
    }
    
    /// 拉伸图片
    ///
    /// - Parameters:
    ///   - topCap: 上端盖高度
    ///   - leftCap: 左端盖高度
    ///   - bottomCap: 下端盖高度
    ///   - rightCap: 右端盖高度
    ///   - finalImgSize: 图片最后的大小
    /// - Returns: 拉伸后的图片
    func qs_stretch(topCap: CGFloat, leftCap: CGFloat, bottomCap: CGFloat, rightCap: CGFloat, finalImgSize: CGSize) -> UIImage {
        let insets = UIEdgeInsetsMake(topCap, leftCap, bottomCap, rightCap)
        // 拉伸图片
        let image = self.resizableImage(withCapInsets: insets, resizingMode: .stretch)
        
        // 绘制图片
        UIGraphicsBeginImageContext(finalImgSize)
        image.draw(in: CGRect.init(x: 0.0, y: 0.0, width: ceil(finalImgSize.width), height: ceil(finalImgSize.height)))
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        
        return newImage ?? self
    }
}
